package top.yxqz.filter.dome;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr.余
 * @date 2022/12/5
 * @package top.yxqz.filter.dome
 * 创建拦截器
 */
public class MyFilterDemo implements Filter {
    private MyFilterConfig filterConfig; //注入自定义的拦截器配置对象
    private FilterConfig config;//注入tomcat中的拦截器配置对象

    /**
     * 初始化过滤器的方法
     *
     * @param filterConfig 过滤器的配置对象
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = new MyFilterConfig();
        config = filterConfig;
        System.out.println("MyFilterDemo初始化成功");
    }


    /**
     * 做拦截处理的方法
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("捕获到了拦截，并做处理");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("text/html;charset=utf-8");
        String username = filterConfig.getInitParameter("username");
        System.out.println("MyFilterConfig拿到的数据：" + username);
        String username1 = config.getInitParameter("username");
        System.out.println("FilterConfig拿到的数据"+username1);

        filterChain.doFilter(servletRequest, servletResponse);
    }


    /**
     * 当前拦截器对象灭亡的时候触发
     */
    @Override
    public void destroy() {
        System.out.println("MyFilterDemo灭亡了");
    }
}
